﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace thinger.VisionDemo
{
    public class TcpRecive
    {
        public TcpClient client = new TcpClient();
        private NetworkStream stream; // 网络流，用于与服务器通信
        public string serverIp = "127.0.0.1";
        public int port = 8080;
        public volatile bool ThreadControl;
        //private static readonly TcpRecive instance = new TcpRecive();
        private static readonly TcpRecive read = new TcpRecive();
        private static readonly TcpRecive read1 = new TcpRecive();
        private static readonly TcpRecive print = new TcpRecive();
        public Thread thread;
        public event EventHandler<string> OnTCPClientRecive;
        public bool isConnect = false;
        //public static TcpRecive Instance
        //{
        //    get { return instance; }
        //}
        public static TcpRecive Read
        {
            get { return read; }
        }

        public static TcpRecive Read1
        {
            get { return read1; }
        }
        public static TcpRecive Print
        {
            get { return print; }
        }
        public bool ConnectServer()
        {
            try
            {
                client = new TcpClient();
                client.Connect(serverIp, port);
            }
            catch (Exception ex)
            {
                OnTCPClientRecive?.Invoke(this, $"1,连接异常错误!");
                isConnect = false;
                return false;
            }
            isConnect = true;
            OnTCPClientRecive?.Invoke(this, $"0,连接{serverIp}成功！");
            stream = client.GetStream();
            return true;
        }
        public bool threadStart()
        {
            if (!ConnectServer())
            {
                isConnect = false;
                return false;
            }
            //创建监听线程
            ThreadControl = true;
            isConnect = true;
            thread = new Thread(new ThreadStart(RecieveMessage));
            thread.IsBackground = true;
            thread.Start();
            return true;
        }
        public void RecieveMessage()
        {
            while (ThreadControl)
            {
                try
                {
                    //创建一个缓冲区
                    byte[] bytesReceived = new byte[1024];
                    int bytesRead = stream.Read(bytesReceived, 0, bytesReceived.Length);
                    if (bytesRead > 0)
                    {
                        string msg = Encoding.UTF8.GetString(bytesReceived, 0, bytesRead);
                        msg = msg.Trim();
                        if (!string.IsNullOrEmpty(msg))
                        {
                            OnTCPClientRecive?.Invoke(this, $"0,{msg}");
                        }
                    }
                }
                catch (Exception ex)
                {
                    threadEnd();
                }
            }
        }
        public void sendMsg(string message)
        {
            if (stream == null || client == null)
            {
                OnTCPClientRecive?.Invoke(this, $"1,连接异常错误！");
                return;
            }
            try
            {
                byte[] bytesToSend = Encoding.Default.GetBytes(message);
                // 发送消息
                stream.Write(bytesToSend, 0, bytesToSend.Length);
                OnTCPClientRecive?.Invoke(this, $"0,服务端：{message}");
            }
            catch (Exception)
            {

                threadEnd();
            }

        }
        public void threadEnd()
        {
            isConnect = false;
            ThreadControl = false;
            thread?.Abort();
            client?.Close();
            //client?.Dispose();
            OnTCPClientRecive?.Invoke(this, $"1,{serverIp}断开连接！");
        }

    }
}
